# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  def content_menu_item(link)
    "
    <table>
    <tr>
      <td class=\"contentmenu\" background=\"/images/contentmenu/leftside.jpg\" width=\"13\">&nbsp;</td>
                    <td class=\"contentmenu\">&nbsp;#{link}&nbsp;</td>
        <td class=\"contentmenu\" background=\"/images/contentmenu/rightside.jpg\" width=\"13\">&nbsp;</td>
                  </tr>
          </table>
    "
  end

  def top_menu_item(link)
    "
    <table>
    <tr>
      <td class=\"topmenu\" background=\"/images/topmenu/leftside.jpg\" width=\"13\">&nbsp;</td>
                    <td class=\"topmenu\">&nbsp;#{link}&nbsp;</td>
        <td class=\"topmenu\" background=\"/images/topmenu/rightside.jpg\" width=\"13\">&nbsp;</td>
                  </tr>
          </table>
    "
  end

  def menu_item(link)
    "
    <table>
    <tr>
      <td class=\"menu\" background=\"/images/menu/leftside.jpg\" width=\"18\">&nbsp;</td>
                    <td class=\"menu\">&nbsp;#{link}&nbsp;</td>
        <td class=\"menu\" background=\"/images/menu/rightside.jpg\" width=\"18\">&nbsp;</td>
                  </tr>
          </table>
    "
  end

  def current_user
    session[:user].firstname
  end

  def online
    if session[:user]
      return true
    end
    return false
  end

  def button_to_remote(title, controller, action, id, onclick = "")
    if (onclick.to_s).eql?("wait".to_s)
      onclick = "this.disabled=true;this.value='Vänta...';"
    end
    form_remote_tag(:url => { :controller => controller, :action => action, :id => id }) + submit_tag( title, :onclick => onclick) + "</form>"
  end

  def save_and_continue_button(id = "submit_id")
    submit_tag "Spara och gå till nästa steg", :id => id
  end

  def save_and_continue_form(button_id = "submit_id")
    form_remote_tag(:url => { :action => "guide", :id => "next" }, :loading=>"Form.Element.disable(#{button_id})", :complete=>"Form.Element.enable(#{button_id})" ) + save_and_continue_button(button_id) + "</form>"
  end

  def ad_image_tag(ad,size)
    if ad.pictures.first
      return image_tag(url_for(:controller => :image, :action => size, :id => ad.pictures.first), :alt => "#{size} image")
    end

    return image_tag("/images/noimage-#{size}.jpg", :alt => "No image")
  end

  def category_path(category,includestart=false,make_links=true,province=nil,county=nil,query='')
    if category.category_id != 0
      return category_path(category.category,includestart,make_links,province,county) +
        "<font class='regulartext'> / </font>" +
        (make_links ? link_to(category.name,
          category_url(category,province,county),
          :onclick => "go_to_category('#{category.to_param}','#{query}'); return false;") : category.name)
    elsif includestart
      (make_links ? link_to("Start", url_for( :controller => :category, :action => :all ),
          :onclick => "go_to_category('',''); return false;") : "Start")
    else
      return ""
    end
  end

  #/:province_name/:province/:county_name/:county/*category_path/:category
  def filter_url_hash(category=nil,province=nil,county=nil)
    url = Hash.new

    if category
      url[:category_name] = category.to_param
      url[:category] = category
    end

    if province
      url[:province_name] = province.to_param
      url[:province] = province
    end

    if county
      url[:county_name] = county.to_param
      url[:county] = county
    end
    
    return url
  end

  def category_url_hash(category=nil,province=nil,county=nil,query=nil)
    url = filter_url_hash(category,province,county)

    if query && query != ""
      url[:query] = query
    end

    return url
  end

  def category_url(category=nil,province=nil,county=nil,query=nil)
    url = "/"

    if province
      url += "#{province.to_param}/"
    end

    if county
      url += "#{county.to_param}/"
    end

    if query && query != ""
      url += "search/#{query}/"
    else
      url += "browse/"
    end

    if category
      url += "#{category.to_param}/"
    end

    url
  end

  def decode_string(str)
    str.gsub(/\n/, '<br>')
  end

  def time_from_now(time)
    seconds = (time-Time.now).round
    if (seconds < 0)
      return "0 sekunder"
    end
    days = seconds/(24*3600)
    seconds -= days * 24 * 3600
    hours = seconds/3600
    seconds -= hours * 3600
    minutes = seconds/60
    seconds -= minutes * 60
    if (days > 0)
      return "#{days} dagar, #{hours} timmar, #{minutes} minuter och #{seconds} sekunder"
    elsif hours > 0
      return "#{hours} timmar, #{minutes} minuter och #{seconds} sekunder"
    elsif minutes > 0
      return "#{minutes} minuter och #{seconds} sekunder"
    elsif seconds > 0
      return "#{seconds} sekunder"
    end
  end

  #def iframe(url,width,height)
  #  "<iframe src=\"#{url}\" style=\"height:#{height}; width:#{width};\"></iframe>"
  #end

  #Creates a perfect table with the objects in map[:entities] using the partial
  #in map[:partial] to render each entity.
  #Examples:
  # This will create a HTML table with the width of 800px, every entity will
  # get 250px (so 750px will be used for entities and the rest will be empty
  # filler columns in the table), each entity will be rendered using partial
  # <%= render_table(:entities => @entities,
  #             :width_area => 800,
  #              :width_entity => 250,
  #              :partial => "partial") %>
  #
  # This will do the same thing as above but with a few extra options. Only 4
  # rows of entities will be displayed at the most. Each entity will get an
  # extra value passed to it as a local.
  # <%= render_table(:entities => @entities,
  #             :width_area => 800,
  #              :width_entity => 250,
  #              :partial => "partial",
  #              :rows => 4,
  #              :locals => { :local => "local value" }) %>

  def render_table(map = {})
    output = ""
    if map[:entities]
      count_items = map[:entities].size
      columns = (map[:width_area] / map[:width_entity] - 0.5).round
      rows = 9999 unless map[:rows]
      sub_locals = Hash.new
      sub_locals = sub_locals.merge(map[:locals]) if map[:locals]
      
      spacers = columns-1
      spacer_width = (map[:width_area] - map[:width_entity] * columns) / spacers

      if map[:entities].size > 0
        output += "<table>"
        output += "<tr>"
        current_column = 0
        row = 0
        map[:entities].each do |entity|
          sub_locals[:entity] = entity
          output += "<td style=\"text-align: center; vertical-align: middle;\" width=\"#{map[:width_entity]}\">"
          current_column += 1
          output += render :partial => map[:partial], :locals => sub_locals

          if map[:entities].last == entity
            (current_column+1).upto(columns) do |index|
              current_column += 1
              output += "</td>"
              output += "<td>"
              output += "&nbsp;"
              if current_column != columns
                output += "</td>"
                output += "<td>"
                output += "&nbsp;"
              end
            end
          end
          output += "</td>"
          if current_column == columns &&
              map[:entities].last != entity
            row += 1
            if row == rows
              break
            end
            output += "</tr>"
            output += "<tr>"
            current_column = 0
          else
            output += "<td width=\"#{spacer_width}\">"
            output += "&nbsp;"
            output += "</td>"
          end
        end
        output += "</tr>"
        output += "</table>"
      end
    end
  end


  def render_target(data,target,spinner=nil)
    if data
      render :partial => "#{target[:controller]}/#{target[:action]}"
    else
      render_remote_url(url_for(target),spinner)
    end
  end

  def render_remote_url(url,spinner=nil)
    #layer = "remote_layer_#{rand(99999)}_#{Time.now.to_f}"
    layer = Digest::SHA1.hexdigest("#{url}#{rand(Time.now.to_f)}#{rand(9999)}") unless layer
    output = ""
    if spinner
      output += image_tag("ajax/#{spinner}.gif", :id => "spinner_#{layer}")
    end
    output += "
               <div id=\"#{layer}\">
               <script language=\"javascript\">
               <!--
    "
    if spinner
      output += remote_function(:update => layer,
        :url => "#{url}",
        :method => :get,
        :complete => "$('spinner_#{layer}').hide()")
    else
      output += remote_function(:update => layer,
        :method => :get,
        :url => "#{url}")
    end
    output += "
              //-->
               </script>
               </div>"
    output
  end

  def ad_link(ad,title=nil)
    link_to((title ? title : ad.title),
      "/#{ad.to_param}",
      :onclick => "go_to_url_spinner('/#{ad.to_param}'); return false;")
  end

  def content_link title, url, options = {}
    link_to(title,
      "#{url_for(url)}",
      :onclick => ("go_to_url_spinner('#{url_for(url)}'); return false;" if options[:use_onclick] != false),
      :class => (options[:class] if options[:class]))
  end

  def link_to_spinner title, url, update
    link_to(title,
      "#{url_for(url)}",
      :onclick => ("go_to_spinner('#{url_for(url)}','#{update}'); return false;"))
  end

  def link_to_ajax title, url, update, options = {}
    link_to(title,
      "#{url_for(url)}",
      :onclick => ("go_to('#{url_for(url)}','#{update}'); return false;"),
      :class => (options[:class] if options[:class]))
  end

  def spinner(id,image="spinner_bar")
    output = image_tag "ajax/#{image}.gif", :id => id
    output += "
      <script language=\"javascript\">
      <!--
      $('#{id}').hide();
      //-->
      </script>
    "
    return output;
  end

end
